/*
 * Created by JFormDesigner on Fri Jun 11 16:11:21 CST 2021
 */

package view;

import controller.ServerController;
import entity.User;
import service.UserService;
import service.ServerThread;
import tools.ThreadManage;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class ServerView extends JFrame implements ActionListener {

    private ServerController server;
    private static DateFormat dateFormat;//日期解析

    public ServerView() {
        dateFormat = new SimpleDateFormat("yyyy-MM-dd a hh:mm:ss");
        initComponents();
    }

    /**
     * 用于在日志面板显示信息
     *
     * @param str
     */
    public static void printLog(String str) {
        textArea2.append(dateFormat.format(new Date()) + ": " + "\n" + str + "\n" + "-------------------------------" + "\n\n");
        JScrollBar verticalScrollBar = scrollPane1.getVerticalScrollBar();
        verticalScrollBar.revalidate();
        int maximum = verticalScrollBar.getMaximum();
        verticalScrollBar.setValue(maximum);
    }

    /**
     * 更新线程数
     */
    public static void setThreadCount() {
        label5.setText(String.valueOf(Thread.activeCount()));
    }

    /**
     * 显示用户列表
     */
    public static void showUserList() {
        DefaultTableModel model = (DefaultTableModel) table1.getModel();
        model.setRowCount(0);// 清空table

        Hashtable<Integer, ServerThread> threads = ThreadManage.getThreads();
        ArrayList<User> userList = new UserService().getUserList();

        // 向table中添加内容
        for (User user : userList) {
            String onlineState = "离线";
            if (threads.get(user.getQq()) != null) {
                onlineState = "在线";
            }
            model.addRow(new String[]{user.getNickname(), String.valueOf(user.getQq()), onlineState});
        }

        //绘制状态列的字体颜色
        TableColumn stateColumn = table1.getColumn("状态");
        DefaultTableCellRenderer fontColor = new DefaultTableCellRenderer() {
            public void setValue(Object value) { //重写setValue方法，从而可以动态设置列单元字体颜色
                String s = (String) value;
                setForeground(("在线".equals(s)) ? Color.green : Color.gray);
                setText(s);
            }
        };
        stateColumn.setCellRenderer(fontColor);
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        // Generated using JFormDesigner Evaluation license - unknown
        scrollPane1 = new JScrollPane();
        textArea2 = new JTextArea();
        scrollPane2 = new JScrollPane();
        table1 = new JTable();
        panel1 = new JPanel();
        label1 = new JLabel();
        label2 = new JLabel();
        label3 = new JLabel();
        label4 = new JLabel();
        label5 = new JLabel();
        label6 = new JLabel();
        label7 = new JLabel();
        label8 = new JLabel();
        label9 = new JLabel();
        label10 = new JLabel();
        button1 = new JButton();

        //======== this ========
        setVisible(true);
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //======== scrollPane1 ========
        {
            scrollPane1.setViewportView(textArea2);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(5, 25, 245, 450);

        //======== table1 ========
        String[] columns = {"用户名", "qq", "状态"};//字段
        DefaultTableModel model = new DefaultTableModel(null, columns);
        table1 = new JTable(model);

        //======== scrollPane2 ========
        {
            scrollPane2.setViewportView(table1);
        }
        contentPane.add(scrollPane2);
        scrollPane2.setBounds(255, 25, 340, 260);

        //======== panel1 ========
        {
            panel1.setLayout(null);

            //---- label1 ----
            label1.setText("\u4e3b\u673a\u540d");
            label1.setHorizontalAlignment(SwingConstants.RIGHT);
            panel1.add(label1);
            label1.setBounds(40, 15, 80, label1.getPreferredSize().height);

            //---- label2 ----
            label2.setText("IP\u5730\u5740");
            label2.setHorizontalAlignment(SwingConstants.RIGHT);
            panel1.add(label2);
            label2.setBounds(40, 40, 80, 15);

            //---- label3 ----
            label3.setText("\u542f\u52a8\u65f6\u95f4");
            label3.setHorizontalAlignment(SwingConstants.RIGHT);
            panel1.add(label3);
            label3.setBounds(40, 65, 80, 15);

            //---- label4 ----
            label4.setText("\u7ebf\u7a0b\u603b\u91cf");
            label4.setHorizontalAlignment(SwingConstants.RIGHT);
            panel1.add(label4);
            label4.setBounds(40, 90, 80, 15);

            //---- label5 ----
            label5.setText("");
            label5.setHorizontalAlignment(SwingConstants.LEFT);
            panel1.add(label5);
            label5.setBounds(130, 90, 180, 15);

            //---- label6 ----
            label6.setText("");
            label6.setHorizontalAlignment(SwingConstants.LEFT);
            panel1.add(label6);
            label6.setBounds(130, 65, 180, 15);

            //---- label7 ----
            label7.setText("");
            label7.setHorizontalAlignment(SwingConstants.LEFT);
            panel1.add(label7);
            label7.setBounds(130, 40, 180, 15);

            //---- label8 ----
            label8.setText("");
            label8.setHorizontalAlignment(SwingConstants.LEFT);
            panel1.add(label8);
            label8.setBounds(130, 15, 180, 15);
        }
        contentPane.add(panel1);
        panel1.setBounds(260, 290, 330, 120);

        //---- label9 ----
        label9.setText("\u7cfb\u7edf\u65e5\u5fd7");
        contentPane.add(label9);
        label9.setBounds(10, 10, 140, label9.getPreferredSize().height);

        //---- label10 ----
        label10.setText("\u7528\u6237\u5217\u8868");
        contentPane.add(label10);
        label10.setBounds(new Rectangle(new Point(260, 10), label10.getPreferredSize()));

        //---- button1 ----
        button1.setText("启动服务器");
        button1.addActionListener(this);
        contentPane.add(button1);
        button1.setBounds(255, 425, 335, 47);

        contentPane.setPreferredSize(new Dimension(600, 505));
        pack();
        setLocation(0, 0);
//        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    // Generated using JFormDesigner Evaluation license - unknown
    private static JScrollPane scrollPane1;
    private static JTextArea textArea2;
    private JScrollPane scrollPane2;
    private static JTable table1;
    private JPanel panel1;
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private static JLabel label5;
    private JLabel label6;
    private JLabel label7;
    private JLabel label8;
    private JLabel label9;
    private JLabel label10;
    private JButton button1;

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton source = (JButton) e.getSource();
        if (source.getText().equals("启动服务器")) {
            server = new ServerController();
            showUserList();
            InetAddress ia = null;
            try {
                ia = InetAddress.getLocalHost();
                String host = ia.getHostName();// 获取计算机主机名
                String IP = ia.getHostAddress();// 获取计算机IP
                label5.setText(String.valueOf(Thread.activeCount()));
                label6.setText(dateFormat.format(new Date()));
                label7.setText(IP);
                label8.setText(host);
                source.setText("关闭服务器");
            } catch (UnknownHostException unknownHostException) {
                unknownHostException.printStackTrace();
            }
        } else {
            label5.setText("");
            label6.setText("");
            label7.setText("");
            label8.setText("");
            textArea2.setText("");
            DefaultTableModel model = (DefaultTableModel) table1.getModel();
            model.setRowCount(0);
            printLog("服务器已关闭...");
            source.setText("启动服务器");
            server.myStop();
        }
    }
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
